import { defineStore } from 'pinia';
import { store } from '@/store';
import { getPhoneNumber, login, logOut, userInfo } from '@/api/login';
import type { CocInfo, IGetPhoneNumber, IUserInfo } from '@/api/login/types';
import { CacheEnum } from '@/enums/cacheEnum';
import { switchTab } from '@/router';
import { TabbarPageEnum } from '@/enums/pageEnum';
import { ThridTypeEnum } from '@/enums/loginEnum';
import { Toast } from '@/utils';
import type { UnitListResult } from '@/api/mine/types';
import { unitList } from '@/api/mine';
import { isLogin } from '@/utils/is';
import type { PagesType } from '@/router/types/pages';

interface UserState {
  userInfo: IUserInfo;
  unitList: UnitListResult[]
  token: string;
  tenantId: string;
  currentCocId: number | null;
  cocInfo: CocInfo;
  openOfficialAccount: boolean; // 是否打开公众号弹窗
  // 是否显示完善资料弹窗
  isShowPerfectInfoDialog: boolean
}

const createState = (): UserState => ({
  userInfo: uni.getStorageSync(CacheEnum.userInfo),
  token: uni.getStorageSync(CacheEnum.token),
  tenantId: uni.getStorageSync(CacheEnum.tenantId),
  currentCocId: uni.getStorageSync(CacheEnum.currentCocId),
  cocInfo: uni.getStorageSync(CacheEnum.cocInfo),
  openOfficialAccount: false,
  isShowPerfectInfoDialog: false,
  unitList: []
});

export const useUserStore = defineStore({
  id: 'user',
  state: () => createState(),
  getters: {
    getUnitList: (state) => state.unitList,
    /** 获取权限列表 */
    getMenuVoList: (state) => state.userInfo?.sysUser?.menuVoList || []
  },
  actions: {
    /**
     * @description 获取单位列表
     * @date 14/07/2023
     */
    async setUnitList() {
      const res = await unitList();
      this.unitList = res ?? []
      return this.unitList
    },

    /**
     * @description 验证个人资料是否完善
     * @date 04/07/2023
     */
    validatePerfectionInfo() {
      return new Promise((resolve, reject) => {
        isLogin(() => {
          const { userInfo, setIsShowPerfectInfoDialog } = this

          if (userInfo.isPerfectionInfo) {
            resolve(true)
          } else {
            setIsShowPerfectInfoDialog(true)
            reject('个人资料未完善')
          }
        })
      })
    },

    setIsShowPerfectInfoDialog(bol: boolean) {
      this.isShowPerfectInfoDialog = bol
    },

    async getPhoneNumber(data: IGetPhoneNumber) {
      const r = await getPhoneNumber(data);
      await this.setUserInfo();
      return r;
    },

    /**
     * 微信登录
     * @return {string}  {Promise<string>}
     */
    wxLogin(): Promise<string> {
      return new Promise((resolve, reject) => {
        wx.login({
          success: ({ code }) => {
            resolve(code);
          },
          fail: (err) => reject(err),
        });
      });
    },

    /**
     * 登录
     */
    async login() {
      try {
        const code = await this.wxLogin()
        const res = await login({ code, thridType: ThridTypeEnum.WX3RD })
        this.token = res.token;
        this.tenantId = res.tenantId;
        uni.setStorageSync(CacheEnum.tenantId, res.tenantId);
        uni.setStorageSync(CacheEnum.token, res.token);
        await this.setUserInfo(res.appUser || {});
        return res;
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    },

    /**
     * 获取用户信息
     * @return {*}
     */
    async getuserInfo(): Promise<IUserInfo> {
      return await userInfo(this.token);
    },

    /**
     * 保存用户信息 与 登录状态
     */
    async setUserInfo(userInfo?: IUserInfo) {
      const res = userInfo || await this.getuserInfo();
      this.userInfo = res;
      uni.setStorageSync(CacheEnum.userInfo, res);
      const cocInfo = res.members?.[0] ?? null;
      if (cocInfo) {
        const { cocId } = cocInfo;
        this.currentCocId = cocId;
        uni.setStorageSync(CacheEnum.currentCocId, cocId);
        this.cocInfo = cocInfo;
        uni.setStorageSync(CacheEnum.cocInfo, cocInfo);
      }
      return true;
    },

    /**
     * 检查是否是自己的会员单位
     * @param {number} cocId
     */
    checkIsMyUnit(cocId?: number): Boolean {
      return this.cocInfo?.cocId === cocId;
    },

    /**
     * @description 检查当前路由是否有权限
     * @date 09/04/2024
     * @param {PagesType} key
     * @param {boolean} isButton 是否是按钮
     */
    checkRouterPermission(key: PagesType | string, isButton: boolean = false): boolean {
      return this.getMenuVoList.some(v => v.menuKey === key)
    },

    /** 退出登录 */
    async logOut() {
      await logOut()
      uni.showLoading({ title: '更新身份中...', mask: true })
      this.clearLoginStorage()
      await this.login()
      uni.hideLoading()
      Toast('更新成功', "none", 1500)
    },

    /**
     * @description 清除缓存并重新登录
     * @date 06/03/2024
     */
    async resetApp() {
      this.clearLoginStorage();
      await this.login()
      switchTab(TabbarPageEnum.BASE_HOME)
    },

    /**
     * @description 清除登录缓存
     * @date 06/03/2024
     */
    clearLoginStorage() {
      uni.removeStorageSync(CacheEnum.token);
      uni.removeStorageSync(CacheEnum.userInfo);
      uni.removeStorageSync(CacheEnum.currentCocId);
      uni.removeStorageSync(CacheEnum.cocInfo);
      uni.removeStorageSync(CacheEnum.tenantId);
      uni.removeStorageSync(CacheEnum.localareaData)
      this.$reset()
    },

    /** 清除本地所有缓存信息 */
    async clearLocalAllStorage() {
      uni.clearStorageSync();
      this.$reset()
    },

  },
});

export function useUserStoreWithOut() {
  return useUserStore(store);
}
